from django import http
from alipay import AliPay
from django.conf import settings
from django.shortcuts import render
from django.views import View
import os

from meiduo_mall.utils.response_code import RETCODE
from meiduo_mall.utils.views import LoginRequiredJsonMixin
from orders.models import OrderInfo
from payment.models import Payment


class PaymentView(LoginRequiredJsonMixin, View):
    """对接支付宝的接口"""
    def get(self, request, order_id):
        """
        :param order_id: 订单ID
        :return: JSON
        """
        user = request.user

        try:
            order = OrderInfo.objects.get(order_id=order_id, user=user, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('订单信息错误')

        # 创建对接支付宝接口的SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem'),
            sign_type="RSA2",
            debug=settings.ALIPAY_DEBUG
        )

        # SDK对接支付宝的支付接口，得到登录页的地址
        order_string = alipay.api_alipay_trade_page_pay(
            out_trade_no=order_id,
            total_amount=str(order.total_amount),
            subject='美多商城_%s' % order_id,
            return_url=settings.ALIPAY_RETURN_URL
        )

        alipay_url = settings.ALIPAY_URL + '?' + order_string
        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'alipay_url': alipay_url})


class PaymentStatusView(LoginRequiredJsonMixin, View):
    """保存订单支付状态"""
    def get(self, request):
        # 获取所有查询字符串参数
        query_dict = request.GET
        # 将查询字符串类型转成字典类型
        data = query_dict.dict()
        # 提取并移除 sign,不能参与签名验证
        signature = data.pop('sign')

        # 创建SDK对象
        alipay = AliPay(
            appid=settings.ALIPAY_APPID,
            app_notify_url=None,
            app_private_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/app_private_key.pem'),
            alipay_public_key_path=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'keys/alipay_public_key.pem'),
            sign_type='RSA2',
            debug=settings.ALIPAY_DEBUG   # 指定是否是开发环境
        )

        # 使用SDK对象，调用接口函数，得到验证结果
        success = alipay.verify(data, signature)

        # 若验证通过，将美多订单ID与支付宝订单ID绑定，修改订单状态
        if success:
            # 美多订单ID
            order_id = data.get('out_trade_no')
            # 支付宝订单ID
            trade_id = data.get('trade_no')
            Payment.objects.create(
                order_id=order_id,  # order = order
                trade_id=trade_id
            )
            # 修改订单状态：待支付-->待评价
            OrderInfo.objects.filter(order_id=order_id, status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']).update(status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])

            context = {
                'trade_id': trade_id
            }
            return render(request, 'pay_success.html', context)
        else:
            return http.HttpResponseForbidden('非法请求')